package at.codebase.web.servlets.user;

import java.util.ArrayList;

import at.codebase.core.log.Log;
import at.codebase.db.dao.EUserDao;
import at.codebase.db.entities.EUser;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.URLParameters.ParameterException;
import at.codebase.web.util.servlet.SecureServlet;

public class UserAction extends SecureServlet{

	@Override
	protected RequestType requestType() {
		return RequestType.GET;
	}
	
	@Override
	protected void initSecurityLevels(ArrayList<UserLevel> secLevels) {
		secLevels.add(UserLevel.ADMIN);
		secLevels.add(UserLevel.REGISTERED);
	}
	
	@Override
	protected void processRequestSecurityLevel(RequestInformation requestInfo, UserLevel level, RequestType requestType) {
		if(!tokenCorrect(requestInfo)) {
			processRequestNoAccess(requestInfo, level);
			return;
		}
		
		try {
			String actionType = requestInfo.getParameters().getString("type");
			//Deactivate user
			if(actionType.equals("deactivate")){
				long userId = requestInfo.getParameters().getLong("id");
				EUser user = EUserDao.getUserById(new Long(userId));
				if(user != null){
					if(user.isActive()){
						if(level.equals(UserLevel.ADMIN)){
							user.setActive(false);
							EUserDao.saveUser(user);
							Log.logAdmin(requestInfo.getUser().getId(),
									"Admin (userid="
											+ requestInfo.getUser().getId()
											+ ") deactivated an user (userid="
											+ userId + ")");
						}else{
							//TODO Logging - Unauthorized Change
						}
					}
				}
				redirectTo("/user/"+userId);
			//Activate user
			}else if(actionType.equals("activate")){
				long userId = requestInfo.getParameters().getLong("id");
				EUser user = EUserDao.getUserById(new Long(userId));
				if(user != null){
					if(!user.isActive()){
						if(level.equals(UserLevel.ADMIN)){
							user.setActive(true);
							EUserDao.saveUser(user);
							Log.logAdmin(requestInfo.getUser().getId(),
									"Admin (userid="
											+ requestInfo.getUser().getId()
											+ ") activated an user (userid="
											+ userId + ")");
						}else{
							//TODO Logging - Unauthorized Request
						}
					}
				}
				redirectTo("/user/"+userId);
			}
			
		} catch (ParameterException e) {
			//TODO: Wrong parameter.. Maybe Log this
		}
		
	}
}
